/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */
"use strict";
$(function () {
    org.breezee.page = {
        init: function () {
            var loginCustomerId = $("#_loginCustomerId").val();
            var loginAccountId = $("#_loginAccountId").val();
            if(loginCustomerId != null && loginCustomerId != ""){

                var optionUrl="/api/c666378c5d3b417d8e150c456a489d23@accountId="+loginAccountId;
                var ajaxType="get"
                var optionParam='{"properties":{}}'
                $("#customer_select").attr("optionUrl",optionUrl)
                    .attr("ajaxType",ajaxType)
                    .attr("optionParam", optionParam);

            }else{
                var optionUrl="/api/742445c653654caaa4a1fa69eb651a9a"
                var ajaxType="post"
                var optionParam = '{"properties":{"category":"1"}}';
                $("#customer_select").attr("optionUrl",optionUrl)
                    .attr("ajaxType",ajaxType)
                    .attr("optionParam", optionParam);
            }
            Dolphin.form.parse();
            this._deviceList = this.deviceList("#deviceList");
            this.initEvent();

            this._deviceList.load(('/api/742445c653654caaa4a1fa69eb651a9a'),{
                "parent_id_obj_ae":org.breezee.context.userData.customerId,
                "category":"3",
                "_busiHourFilter" : "1"
            })


        },
        /**
         * 初始化事件
         */
        initEvent: function () {
            let me = this;

            /**
             * 绑定回车事件，触发搜索
             */
            $(document).keypress(function(e) {
                var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
                if (eCode == 13){
                    $(".btn-query").click();
                }
            });

            $(".newShop").click(function () {
                Dolphin.form.empty('.shop-form');
                Dolphin.form.setValue({
                    parent: {
                        id: org.breezee.context.userData.customerId
                    },
                    category: '3',
                    level: '4'
                }, '.shop-form');

                $('#shop_win').modal('show');
                $('#timeZone').val(8);
            });

            $(".customerAccount").click(function () {
                let checked = me._orgTree.getChecked();
                if (checked.length == 0) {
                    Dolphin.alert(Dolphin.i18n.get("store.selectCustomer"));
                    return;
                }
                $("#org_relation_win").modal('show');
            });

            $('.relation_submit').click(function () {
                let data = {};
                data.id = me.selectData.id;
                data.accounts = [];
                let selData = me._selectList.data.rows;
                for (let i = 0; i < selData.length; i++) {
                    data.accounts.push({id: selData[i].id});
                }
                Dolphin.ajax({
                    url: '/api/958ec455d9334fe39839837dccbdc070',
                    type: Dolphin.requestMethod.POST,
                    data: Dolphin.json2string(data),
                    onSuccess: function (reData) {
                        me._accountList.load('/api/756af3ae31a64565a54ec0221f84d377', {
                            "customer_id_obj_ae": me.selectData.id
                        });
                        $('#org_relation_win').modal('hide');
                    }
                });
            });

            $('[change]').click(function () {
                let thisButton = $(this), allFlag = !!thisButton.attr('all'),
                    sourceList, targetList,
                    checkedData,
                    i;
                if (thisButton.attr("change") == "select") {
                    sourceList = me._unSelectList;
                    targetList = me._selectList;
                } else {
                    sourceList = me._selectList;
                    targetList = me._unSelectList;
                }
                if (allFlag) {
                    checkedData = [].concat(sourceList.data.rows);
                } else {
                    checkedData = sourceList.getChecked();
                }
                for (i = 0; i < checkedData.length; i++) {
                    if (!checkedData[i].inheritFlag) {
                        sourceList.removeRow(checkedData[i].__id__);
                        targetList.addRowWithData(checkedData[i]);
                    }
                }
            });

            $('#org_relation_win').on('show.bs.modal', function (e) {
                me._selectList.load('/api/756af3ae31a64565a54ec0221f84d377', {
                    "customer_obj": me.selectData.id,
                    "pageSize": "-1"
                });
                me._unSelectList.load('/api/756af3ae31a64565a54ec0221f84d377', {"customer_obj_not": me.selectData.id});
            });

            $("#deviceAdd").click(function () {
                Dolphin.form.empty('.device-form');
                let checkedData = me._orgTree.getChecked();
                if (checkedData.length == 0 || checkedData[0].category != 3) {
                    Dolphin.alert(Dolphin.i18n.get("store.selectStore"));
                    return;
                }
                Dolphin.form.setValue({
                    customer: {
                        id: checkedData[0].id
                    }
                }, '.device-form');
                $("#device_model").modal('show');
            });
            /**
             * 保存按钮
             */
            $(".btn_submit").click(function () {
                let ef = $("." + $(this).data('cla')), closeWin = $('#' + $(this).data('win'));
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    if (data.parent && !data.parent.id)
                        delete data.parent;
                    data.category = data.category || '3';
                    data.level = data.level || '4';
                    if(data.openDate)
                        data.openDate = data.openDate + " 12:00:00";
                    if(data.closeDate)
                        data.closeDate = data.closeDate + " 12:00:00";
                    //TODO:先这样，后续从后台中过滤掉
                    if(data.parent.id=='9236b103947f4f71b261bcf958286b2c'){
                        Dolphin.alert(Dolphin.i18n.get("store.sonyChina"));
                        return;
                    }
                    Dolphin.ajax({
                        url: '/api/742445c653654caaa4a1fa69eb651a9a',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._deviceList.reload();
                            closeWin.modal('hide');
                        }
                    });

                }
            });

            //导出
            $(".btn-shop-export").click(function () {

                var queryCondition = Dolphin.form.getValue('.query-form');
                console.log(queryCondition);
                // console.log(me._deviceList.opts.queryParams);
                var url = (org.breezee.context.contextPath=='/'?'':org.breezee.context.contextPath) +'/api/a52c2dea88c143849fc722002b59b3f1';
                var form = $("<form />");
                form.attr({"style": "display: none", "target": '_blank', "method": "post", "action": url});
                $('body').append(form);
                $.each(queryCondition, function(key, value){
                    var input = $("<input>");
                    input.attr({"name": key, "value": value, "type": "hidden"});
                    console.log('key : '+key+' | value : '+value);
                    form.append(input);
                });
                form.submit();
                form.remove();
            });
            $(".btn-device-export").click(function () {

                var queryCondition = Dolphin.form.getValue('.query-form');
                console.log(queryCondition);
                // console.log(me._deviceList.opts.queryParams);
                var url = (org.breezee.context.contextPath=='/'?'':org.breezee.context.contextPath) +'/api/cda475fc7f6c496a9757f69eb531499c';
                var form = $("<form />");
                form.attr({"style": "display: none", "target": '_blank', "method": "post", "action": url});
                $('body').append(form);
                $.each(queryCondition, function(key, value){
                    var input = $("<input>");
                    input.attr({"name": key, "value": value, "type": "hidden"});
                    console.log('key : '+key+' | value : '+value);
                    form.append(input);
                });
                form.submit();
                form.remove();
            });

            //查询
            $(".btn-query").click(function () {
                var shopIds = '';
                var shopAreaCondition = $("#customer_select").val();//查询条件 区域
                if( shopAreaCondition != null && shopAreaCondition.length > 0 ){
                    Dolphin.ajax({
                        url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                        type: Dolphin.requestMethod.POST,
                        data: Dolphin.json2string({properties : { "selectCustomerId" : shopAreaCondition , "selectShopType" : ''}}),
                        async: false,
                        loading:true,
                        onSuccess: function (reData) {
                            if(reData.rows){
                                var shopIdArray = $.map(reData.rows,function(n){
                                    return n.id;
                                });
                                shopIds = shopIdArray.join('-');
                            }
                        }
                    });
                }

                var queryCondition = Dolphin.form.getValue('.query-form');
                if($("#followedFlag").is(':checked')){
                    queryCondition.followed = 'Y';
                }else{
                    if(me._deviceList.opts.queryParams.followed)
                        delete me._deviceList.opts.queryParams.followed;
                }
                if($("#customer_select").val()){
                    queryCondition._areaId = shopIds;
                }else{
                    delete me._deviceList.opts.queryParams._areaId;
                }
                console.log(queryCondition);
                console.log(me._deviceList.opts.queryParams);
                me._deviceList.load('', queryCondition);

            });

            $(".device_submit").click(function () {
                let ef = $("." + $(this).data('cla')), closeWin = $('#' + $(this).data('win'));
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    Dolphin.ajax({
                        url: '/api/b6a1808e4fcd4844836eb802249ac30c',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._deviceList.load('/api/b6a1808e4fcd4844836eb802249ac30c', {
                                customer_id_obj_ae: me.selectData.id
                            });
                            closeWin.modal('hide');
                        }
                    });

                }
            });
        },

        /**
         *  设备列表
         * @param panelId
         * @returns {*|LIST}
         */
        deviceList: function (panelId) {
            let me = this;
            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                columns: [{
                    code: 'name',
                    title: Dolphin.i18n.get("store.name")
                }, {
                    code: 'code',
                    title: Dolphin.i18n.get("store.storeCode")
                }, {
                    code: 'parentName',
                    title: Dolphin.i18n.get("store.superior")
                },{
                    code: 'province',
                    title: Dolphin.i18n.get("framework.province")
                }, {
                    code: 'city',
                    title: Dolphin.i18n.get("framework.city")
                },{
                    code: 'openTime',
                    title: Dolphin.i18n.get("store.businessTime"),
                    formatter:function (val,row) {
                        return row.openTime+"-"+row.closeTime;
                    }
                }, {
                    code: 'id',
                    title: '&nbsp;',
                    width: '180px',
                    formatter: function (val, row, index) {
                        return '<a class="btn btn-outline btn-circle btn-sm purple editBtn" data-id="'+row.id+'" href="javascript:;">' +
                            '<i class="fa fa-edit"></i>&nbsp;'+Dolphin.i18n.get("account.edit")+'</a>'
                            +
                            '<a class="btn btn-outline btn-circle btn-sm dark delBtn" data-id="'+row.id+'" href="javascript:;">' +
                            '<i class="fa fa-trash-o"></i>&nbsp;'+Dolphin.i18n.get("role.delete")+'</a>';
                    }
                }],
                multiple: false,
                rowIndex: true,
                checkbox: false,
                ajaxType: Dolphin.requestMethod.POST,
                data: {rows: []},
                pagination: true,
                onLoadSuccess: function (data) {
                    org.breezee.buttons.editCallback('1423c7225d134248944babc34f3a36f4', 'id', function (reData) {
                        reData.value.parent = {
                            id: reData.value.parentId
                        };
                        Dolphin.form.setValue(reData.value, '.shop-form');
                        if(reData.value.openDate){
                            $("#openDate").val(reData.value.openDate.substr(0,10));
                        }else{
                            $("#openDate").val("");
                        }
                        if(reData.value.closeDate){
                            $("#closeDate").val(reData.value.closeDate.substr(0,10));
                        }else{
                            $("#closeDate").val("");
                        }

                        $("#shop_win").modal('show');
                    });
                    org.breezee.buttons.delCallback('1423c7225d134248944babc34f3a36f4', function (reData) {
                        me._deviceList.load('/api/b6a1808e4fcd4844836eb802249ac30c', {
                            customer_id_obj_ae: me.selectData.id
                        });
                    });
                }
            });
        }
    };
    org.breezee.page.init();
});